<template>
	<div class="in-wrap">
		<div class="nxb-box">
			<form method="post" id="addPaperRecord"> <input type="hidden" id="sign" value="6f188ffb169a61d5f652598a929f074d"> <input type="hidden" id="testTime" value=""> <input type="hidden" value="276" id="paperId"> <input type="hidden" value="686" id="paperRecordId"> <input type="hidden" value="527" id="planId">
				<div class="e-main" style="min-height: 936px;">
					<div class="container">
						<div class=" clearfix e-test-box">
							<div class="e-test-fixed ">
								<div id="p-test-box" class="p-test-box1" style="position: fixed;">
									<div class="paper-time-wrap">
										<div class="e-c-box2 " id="continue"><em></em></div>
										<div class="mt15">
											<p class="vam c-aaa fsize14 f-fM">剩余</p>
											<p class="vam fsize18 examTimerShow c-master mt5">{{content}}</p>
										</div>
										<div class="mt20 paper-submit">
											<a title="" @click="submitExamPaper" href="javascript:void(0)">我要交卷</a>
										</div>
									</div>
									<div class="mt20">
										<dl class="paper-test q-card-box q-card-wrap"> <dt> <a href="javascript:;"> <span class="ques-card">答题卡</span> <em class="q-card-icon icon16"></em> </a> </dt>
											<dd class="style-2">
												<div class="ques-card-tab clearfix">

													<span class="fl" v-for="(item,index) in questionRecords" :class="item.answer&&item.answer.length>0?'current':''">
														<a href="javascript:;" :title="'第'+ (index+1) +'题'"  @click="findExam(item.question)" > {{index+1}}</a>
													</span>

												</div>
											</dd>
										</dl>
									</div>
								</div>
							</div>
							<div>
								<div class="p-test-title1 nextTitleAnchor"> <span>{{paperName}}</span> </div>
								<div class="t-p-sub-title-wrap">
									<div class="t-p-sub-title">
										<ul class="clearfix">
											<li v-for="item in paperTypeList" :class="examType == item.type?'current':''">
												<a class="titleHeiddenAndShow0" href="javascript:void(0)" :title="item.name" @click="changExamType(item)">
													<strong>{{item.name}}</strong>
													<span></span>
												</a>
											</li>

										</ul>
									</div>
								</div>
								<div class="clear"></div>

								<div class="p-ques-list">
									<ul>

										<li class="p-q-item" v-for="(item,index) in paperList" v-show="examType == item.type">
											<div class="pt10 pb10 pl10 pr10">
												<h6 class="hLh30 of unFw " v-show="item.type == '1'">
														<font class="c-333 fsize12" id="showTitleValue">每题有且只有1个正确答案[&nbsp;每小题{{item.score}}分&nbsp;]</font>
													</h6>
											</div>
											<div class="pt10 pb10 pl10 pr10" v-show="item.type == '2'">
												<h6 class="hLh30 of unFw ">
														<font class="c-333 fsize12" id="showTitleValue">每题至少1个正确选项[ 每小题{{item.score}}分 ]</font>
													</h6>
											</div>
											<div class="pt10 pb10 pl10 pr10" v-show="item.type == '3'">
												<h6 class="hLh30 of unFw ">
														<font class="c-333 fsize12" id="showTitleValue">判断对错[ 每小题{{item.score}}分 ]</font>
													</h6>
											</div>
											<div class="pt10 pb10 pl10 pr10" v-show="item.type == '4'">
												<h6 class="hLh30 of unFw ">
														<font class="c-333 fsize12" id="showTitleValue">阅读题干，填写问题[ 每小题{{item.score}}分 ]</font>
													</h6>
											</div>
											<div class="pt10 pb10 pl10 pr10" v-show="item.type == '5'">
												<h6 class="hLh30 of unFw ">
														<font class="c-333 fsize12" id="showTitleValue">阅读题干，填写问题[ 每小题{{item.score}}分 ]</font>
													</h6>
											</div>

											<article class="datikaQstAnchor1 t-paper-one t-paper-check-box" v-if="item.type == '1'" v-for="childItem in item.questionList" :ref="childItem.id">

												<div class="clearfix p-ques-title">
													<tt class="fl">{{childItem.paperNum}}</tt>

													<span class="c-333 fsize16 fl" v-html="childItem.info"></span>
												</div>
												<section class="t-p-options">
													<ol>
														<li v-for="optItem in childItem.optionList">
															<a href="javascript:void(0);">{{optItem.name}}、<span v-html="optItem.info"></span></a>
														</li>

													</ol>
												</section>
												<section class="is-options clearfix">
													<div class="fl t-p-is-options">
														<el-radio v-model="questionRecords[childItem.paperNum-1].answer" :label="optItem.name" v-for="(optItem,optIndex) in childItem.optionList" :key="optIndex">{{optItem.name}}</el-radio>

													</div>
													<input class="ml10" value="" type="hidden" name="record[0].userAnswer">
												</section>

											</article>

											<article class="datikaQstAnchor31 t-paper-one t-paper-check-box" v-if="item.type == '2'" v-for="childItem in item.questionList" :ref="childItem.id">
												<div class="clearfix p-ques-title">
													<tt class="fl">{{childItem.paperNum}}</tt>

													<span class="c-333 fsize16 fl" v-html="childItem.info"></span>
												</div>
												<section class="t-p-options">
													<ol>
														<li v-for="optItem in childItem.optionList">
															<a href="javascript:void(0);">{{optItem.name}}、<span v-html="optItem.info"></span></a>
														</li>

													</ol>
												</section>
												<section class="is-options clearfix">
													<div class="fl t-p-is-options">
														<el-checkbox-group v-model="questionRecords[childItem.paperNum-1].answer">
															<el-checkbox v-for="(optItem,optIndex) in childItem.optionList" :label="optItem.name" :key="optIndex"></el-checkbox>
														</el-checkbox-group>
													</div>

												</section>
											</article>

											<article class="datikaQstAnchor31 t-paper-one t-paper-check-box" v-if="item.type == '3'" v-for="childItem in item.questionList" :ref="childItem.id">
												<div class="clearfix p-ques-title">
													<tt class="fl">{{childItem.paperNum}}</tt>

													<span class="c-333 fsize16 fl" v-html="childItem.info"></span>
												</div>
												<section class="t-p-options">
													<ol>
														<li v-for="optItem in childItem.optionList">
															<a href="javascript:void(0);">{{optItem.name}}、<span v-html="optItem.info"></span></a>
														</li>

													</ol>
												</section>
												<section class="is-options clearfix">
													<div class="fl t-p-is-options">
														<el-radio v-model="questionRecords[childItem.paperNum-1].answer" label="true">正确</el-radio>
														<el-radio v-model="questionRecords[childItem.paperNum-1].answer" label="false">错误</el-radio>

													</div>

												</section>
											</article>

											<article class="t-paper-one t-paper-check-box" v-if="item.type == '4'" v-for="childItem in item.questionList" :ref="childItem.id">
												<div class="clearfix p-ques-title">
													<tt class="fl">{{childItem.paperNum}}</tt>
													<span class="c-333 fsize16 fl" v-html="childItem.info"></span>
												</div>

												<section class="ques-tk-wrap" v-for="(optItem, optIndex) in getCompletionOpt(childItem.correct)">
													<p>
														<span style="width: 30%;">答案{{optIndex+1}}：</span><el-input v-model="questionRecords[childItem.paperNum-1].answer[optIndex]" style="width: 70%;"></el-input>
													</p>
													
												</section>

											</article>

											<article class="datikaQstAnchor46 t-paper-one t-paper-check-box" v-if="item.type == '5'" v-for="childItem in item.questionList" :ref="childItem.id">
												<div class="clearfix p-ques-title">
													<tt class="fl">{{childItem.paperNum}}</tt>

													<span class="fl c-333 fsize16" v-html="childItem.info"></span>
												</div>
												<div class="textarea-box">
													<el-input type="textarea" :rows="3" placeholder="请输入内容" v-model="questionRecords[childItem.paperNum-1].answer">
													</el-input>
												</div>
											</article>

											<section class="page-bar" v-show="index<paperList.length-1">
												<span class="comm-btn-wrap"><a href="javascript:;" title="点击进入下一部分" class="comm-btn c-btn-1" @click="nextPaper">下一部分</a></span>
											</section>
										</li>

									</ul>

								</div>
							</div>
						</div>
					</div>
				</div>
			</form>
			<div>
				<nav class="global-nav exam-navbox">
					<ul class="clearfix">
						<li>
							<a class="bor-right" href="javascript:;"> <em class=" clock-icon vam"></em> <span class="vam examTimerShow">28分46秒</span> </a>
						</li>
						<li>
							<a class="bor-right" onclick="formSubmit()" href="javascript:;"> <em class="mr5 paper-sub-icon vam"></em> <span class="fsize16 c-333 vam">提交</span> </a>
						</li>
						<li id="gn-ul">
							<a id="learn-history" href="javascript:;"> <em class="icon16 mr10 answer-card"></em> <span class="fsize16 c-333 vam">答题卡</span> </a>
						</li>
					</ul>
				</nav>

			</div>

		</div>
	</div>
</template>

<script>
	import { getExamPaper, submitExam } from '@/api/exam'
	import { MessageBox,Notification  } from 'element-ui';
	export default {

		name: 'exam',
		data() {

			return {
				timeStr:null,
				paperName: "",
				paperId:0,
				paperType:"",
				time: "",
				paperTypeList: [], //试题类型
				paperList: [], //试题数组
				examType: '',
				questionRecords: [], //答案数组
				examRecordId: "", //考试记录id
				content:"",//倒计时内容
				seconds:0,
				examId:0,
				taskId:''//培训id
				
			}
		},
		computed: {
			userInfo() {
				return this.$store.getters.getStorageInfo;
			}
		},
		created() {
			let query = this.$route.query;
			this.paperName = query.name;
			switch (query.type){
				case 'COURSE':
				this.examId = query.courseId;
					break;
				case 'EXAM':
				this.examId = query.examId;
					break;
				case 'TASK':
				this.examId = query.itemId;
				this.taskId = query.taskId;
					break;
				default:
					break;
			};
			this.paperType = query.type;
			this.paperId = query.paperId;
			this.getExamPaper(query.paperId, query.type);
		},
		methods: {
			ScrollTop(number = 0, time) { //点击答题卡滚动动画

				if(!time) {
					document.body.scrollTop = document.documentElement.scrollTop = number;
					return number;
				}
				const spacingTime = 20; // 设置循环的间隔时间  值越小消耗性能越高
				let spacingInex = time / spacingTime; //计算循环的次数
				let nowTop = document.body.scrollTop + document.documentElement.scrollTop; // 获取当前滚动条位置
				let everTop = (number - nowTop) / spacingInex; // 计算每次滑动的距离
				let scrollTimer = setInterval(() => {
					if(spacingInex > 0) {
						spacingInex--;
						this.ScrollTop(nowTop += everTop);
					} else {
						clearInterval(scrollTimer); // 清除计时器
					}
				}, spacingTime);

			},

			getExamPaper(id, type) { //获取试卷 type,考试形式 ，用于创建考试记录接口
				getExamPaper(id).then((res) => {
					let data = res.entity;
					let paperNum = 0;
					this.time = data.time;
					data.paperStemList.forEach((item) => {
						this.paperTypeList.push({
							"name": item.name,
							"type": item.type
						});
						for(let i = 0; i < item.questionList.length; i++) {
							if(item.questionList) {
								paperNum += 1;
								item.questionList[i]["paperNum"] = paperNum;
								let questionData = {
									answer: '',
									score: item.score,
									question: item.questionList[i]
								};
								if(item.type == 2 || item.type == 4) {
									questionData.answer = [];
								};
								this.questionRecords.push(questionData);

							}
						}
					});
					this.paperList = data.paperStemList;
					this.examType = this.paperTypeList[0].type;
					let userId = this.$store.getters.getStorageInfo.id;
					this.countdowm(data.time);
				})
			},
			changExamType(val) { //切换试题类型

				this.examType = val.type;
			},
			nextPaper() { //点击下一部分
				let nextType = this.findNextExam(this.examType);
				this.examType = nextType;
			},
			getCompletionOpt(val) { //填空题根据答案显示多少个选项
				let correctArry = val.split(';');
				return correctArry;
			},
			getCompletion(arry){//填空题形式
				let postStr = '';
 				arry.forEach((item)=>{
 					postStr+=';'+item;
	 			});
	 			postStr = postStr.substr(1);
	 			return postStr;
			},
			findExam(val) { //点击答题卡寻找试题
				this.examType = val.type;
				let examId = val.id;
				let elementObj = this.$refs[examId][0];
				let that = this;
				setTimeout(function() {
					that.ScrollTop(elementObj.offsetTop, 200);
				}, 100); //解决元素为display:none时获取offsetTop为0

			},
			findNextExam(type) { //获取下一部分值
				let length = this.paperTypeList.length;
				for(let i = 0; i < length; i++) {
					if(type == this.paperTypeList[i].type) {
						return this.paperTypeList[i + 1].type;
					}
				}
			},
			createExamRecord(data) { //创建考试记录

				createExamRecord(data).then((res) => {
					this.examRecordId = res.entity.id;
				});
			},
			submitExam(data) { //提交试卷
				data.questionRecords.forEach((item)=>{
					switch (item.question.type){
						case 2:
						let str = "";
						item.answer.sort().forEach((item)=>{
							str +=item;
						});
						item.answer = str;
							break;
						case 4:
						item.answer = this.getCompletion(item.answer);
							break;
						default:
							break;
					}
				});
				submitExam(data,{'Content-Type': 'application/json;charset=utf-8'}).then((res) => {
					this.$router.push({
						path: '/paperResults',
						query: {
							examId:this.examId,
							type:this.paperType
						}
					})
				});
			},
			countdowm(timestamp) {      
				let self = this;   
				var startSecond = Number(timestamp*60);  
				var numberSeconds = Number(timestamp*60);    
				self.timeStr = setInterval(function() {        
					if(numberSeconds > 0) {          
						let format = '';    
			         	var minutes = Math.floor(numberSeconds/60);
            			var second = Math.floor(numberSeconds%60);
						format = ""+minutes+"分"+second+"秒";          
						self.content = format;  
						--numberSeconds;    
						self.seconds = Number(startSecond - numberSeconds);    
						
					} else {           
						let data = {
								paperId:self.paperId,
								paperName: self.paperName,
								type: self.paperType,
								userId:self.userInfo.id,
								examId:self.examId,
								time:self.seconds,
								questionRecords:self.questionRecords,
								jsonType:'string',
								questionCount: self.questionRecords.length
						};
						self.content = '已结束'; 
						self.submitExam(data);
						Notification.success({
				          title: '考试结束',
				          message: '考试已结束，提交成功',
				          position: 'top-left'
				        });
						clearInterval(self.timeStr);   
						 self.timeStr = null;
					}         
				}, 1000);        
			},
			submitExamPaper(){//点击我要交卷
				let that = this;
				let data = {
						paperId:this.paperId,
						paperName: this.paperName,
						type: this.paperType,
						userId:this.userInfo.id,
						examId:this.examId,
						time:this.seconds,
						questionRecords:this.questionRecords,
						jsonType:'string',
						questionCount: this.questionRecords.length
				};
				if(this.paperType == 'TASK'){
					data["taskId"] = this.taskId;
				};
				if(this.isCompletion()){
					MessageBox.confirm('确定要交卷吗？', '提示', {
			          confirmButtonText: '确定',
			          cancelButtonText: '取消',
			          type: 'success'
			        }).then(() => {
			         	that.submitExam(data);
			        }).catch(() => {
			                  
			        });	
				}else{
					MessageBox.confirm('您还有试题未做完，确定要交卷吗？', '提示', {
			          confirmButtonText: '确定',
			          cancelButtonText: '取消',
			          type: 'warning'
			       }).then(() => {
			        	that.submitExam(data);
			        }).catch(() => {
			                  
			        });
				}
				
			},
			isCompletion(){
				let isExam = false
				this.questionRecords.forEach((item)=>{
					if(item.answer == ""||item.answer == []){
						isExam = false;
					}else{
						isExam = true;
					}
				});
				return isExam;
			}
		

	},
	beforeRouteLeave(to, from, next){

		clearInterval(this.timeStr);
		this.timeStr = null;
		next();
	}
}
</script>

<style scoped lang="scss">
	@import '../../assets/style/examing-style'
</style>